package network.盗版qq.qqserver.service;

import network.盗版qq.comment.Message;
import network.盗版qq.comment.MessageType;
import network.盗版qq.comment.User;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * @author mubei
 * @date 2021/12/6
 * @description 服务器 监听9999  等待客户端的连接   并保持通信
 */
public class QQServer {

    private ServerSocket ss = null;
    // 创建一个集合  存放多个用户  如果是这些用户  就认为是合法的
    private static HashMap<String,User>validUsers = new HashMap<String,User>();
    static {
        validUsers.put("100",new User("100","1"));
        validUsers.put("ah",new User("ah","1"));
        validUsers.put("mubei",new User("mubei","1"));
        validUsers.put("zl",new User("zl","1"));
        validUsers.put("mw",new User("mw","1"));
    }

    /*
    * 建议过关斩将
    * 单点登录
    * */
    private boolean checkUser(String userId,String password){
        if(!validUsers.containsKey(userId)){
            return false;
        }
        if(!validUsers.get(userId).getPassword().equals(password)){
            return false;
        }
        if(ManageServerClientThreads.getServerConnectClientThread(userId)!=null){
            return false;
        }
        return true;
    }

    public QQServer() {
        // 注意  端口可以写在配置文件中
        try {
            // 循环监听
            System.out.println("服务器在9999端口进行监听");
            ss = new ServerSocket(9999);
            // 如果没有客户端连接 会阻塞等待
            while (true) {
                Socket socket = ss.accept();
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                // 第一次读取user对象   返回message
                User user = (User) ois.readObject();
                Message message = new Message();
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                // 验证
                if (checkUser(user.getUserId(), user.getPassword())) {
                    // 登录成功
                    message.setMesType(MessageType.LOGIN_SUCCEED);
                    oos.writeObject(message);
                    oos.flush();
                    // 创建一个线程 和客户端保持通信  该线程需要持有socket对象
                    ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket,user.getUserId());
                    new Thread(() -> serverConnectClientThread.run()).start();
                    ManageServerClientThreads.addServerConnectClientThread(user.getUserId(), serverConnectClientThread);
                } else {
                    // 登录失败
                    System.out.println("用户" + user.getUserId() + " " + user.getPassword() + " 验证失败");
                    message.setMesType(MessageType.LOGIN_FAIL);
                    oos.writeObject(message);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
